"""[summary]
该模块主要用于二维成丝大小的分析
Returns:
    [type] -- [description]
"""
import matplotlib as mpl

mpl.use('Agg')
import sdf_helper as sh
import matplotlib.pyplot as plt
import numpy as np
import analyse as al
from analyse.sim_parm import *

al.sdf_prefix = '1'
al.sdf_scope = [1]
#==========函数==========================================
#=========自定义函数========================================
# # fft 滤波
# ax = plt.subplot(1, 2, 1)
# plt.xlim(0, 50 * micron)
# plt.ylim(-500 * micron, 500 * micron)
# fft_res = np.fft.fft(y_axis)  #注意fft从k=0开始，第一个值为纯实数，几何意义为平均值
# print(fft_res)
# min_dstc = x_axis[1] - x_axis[0]
# fft_fre = np.fft.fftfreq(len(x_axis), min_dstc)
#开始滤波，先求频率域上的平均值，再将频率域上远超平均值的部分舍去
# ifft_res = np.fft.ifft(fft_res)
# ax.scatter(x_axis, ifft_res)
#平均值滤波，删除明显偏移平均值的点

#=================开始处理数据=================================================
x_axis = np.zeros(0)
y_axis = np.zeros(0)
for i in sdf_scope:
    data = sh.getdata('%s%.4d.sdf' % (al.sdf_prefix, i))
    var = data.Electric_Field_Ey
    X = var.grid_mid.data[0][xslice]
    Y = np.linspace(ymin, ymax, ny)
    X, Y = np.meshgrid(X, Y)
    Z = np.zeros([yy - yx, y - x])
    for j in range(yy - yx):
        for k in range(y - x):
            Z[j, k] = var.data[k + x]
    (max_ey_num, max_ey, max_mean,
     max_std) = al.tool.data_analyse(Z, x, y, yx, yy)
    temp_x_axis, temp_y_axis = al.tool.find_nearest_value(
        Z,
        max_ey_num,
        max_ey_num + 1,
        int(yy / 2),
        yy,
        1.0 / np.e * max_ey,
    )
    # print("after find_nearest_value", temp_x_axis, temp_y_axis)
    temp_x_axis, temp_y_axis = al.tool.cal_coordinate(temp_x_axis, temp_y_axis,
                                                      0, 0)
    # print("after cal_coordinate", temp_x_axis, temp_y_axis)
    x_axis = np.append(x_axis, temp_x_axis[0])
    y_axis = np.append(y_axis, temp_y_axis[0])
print("============test1===============================")
print(temp_x_axis, temp_y_axis)
print(x_axis, y_axis)
ax = plt.subplot(1, 1, 1)
ax.plot(x_axis, y_axis, label="simulation_spotsize", color='b')

Pc = 17.5 * (al.mathfunc.omega_1 / al.mathfunc.omega_pe)**2 * 1e9
print(Pc)
for i in range(len(x_axis)):
    y_axis[i] = np.sqrt(al.mathfunc.w0_1**2 *
                        (1 + (x_axis[i] / al.mathfunc.xr_1)**2 *
                         (1 - al.mathfunc.laserin_1 * np.pi *
                          (al.mathfunc.w0_1 * 1e2)**2 / Pc)))
print("============test1===============================")
print(x_axis, y_axis)
ax.plot(x_axis, y_axis, label="theoretic-spotsize", color='k')
ax.legend()
print('savefig')
plt.savefig('test')
plt.close()